<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">污染预测模块</text>
      <text class="subtitle">基于设备位置的AI智能预测分析</text>
    </view>

    <!-- 地图容器 -->
    <view class="map-container" :class="{ 'fullscreen': isMapFullscreen }">
      <view class="map-header">
        <text class="map-title">监测点分布与污染预测</text>
        <view class="header-right">
          <button class="location-btn" @click="toggleMapFullscreen">
            <uni-icons type="arrowup" size="18"></uni-icons>
            <text class="location-text">{{ isMapFullscreen ? '还原' : '放大' }}</text>
          </button>
          <text class="device-count">设备总数: {{ deviceList?.length || 0 }}</text>
          <button class="location-btn" @click="requestLocation">
            <text class="location-icon">📍</text>
            <text class="location-text">定位</text>
          </button>
        </view>
      </view>

      <!-- 用户位置信息 -->
      <view class="user-location" v-if="userLocation?.address">
        <text class="location-text">📍 {{ userLocation.address }}</text>
        </view>
      
      <!-- 腾讯地图组件 -->
      <!-- #ifdef H5 -->
      <view id="tencentMap" class="map-component"></view>
      <!-- #endif -->

      <!-- #ifdef MP-WEIXIN -->
      <map
        id="tencentMap"
        class="map-component"
        :longitude="mapConfig?.center?.[0] || 115.489120"
        :latitude="mapConfig?.center?.[1] || 38.814788"
        :scale="mapConfig?.zoom || 10"
        :markers="markers"
        :show-location="true"
        :enable-3D="false"
        :enable-overlooking="false"
        :enable-zoom="true"
        :enable-scroll="true"
        :enable-rotate="false"
        :enable-satellite="false"
        :enable-poi="true"
        :show-compass="false"
        :show-scale="true"
        :min-scale="3"
        :max-scale="20"
        :key="mapConfig?.key"
        @markertap="onMarkerTap"
        @regionchange="onRegionChange"
        @updated="onMapUpdated"
        @tap="onMapTap"
      >
        <cover-view class="map-legend">
          <cover-view class="legend-item">
            <cover-view class="legend-color online"></cover-view>
            <cover-text class="legend-text">在线</cover-text>
          </cover-view>
          <cover-view class="legend-item">
            <cover-view class="legend-color offline"></cover-view>
            <cover-text class="legend-text">离线</cover-text>
          </cover-view>
          <cover-view class="legend-item">
            <cover-view class="legend-color fault"></cover-view>
            <cover-text class="legend-text">故障</cover-text>
          </cover-view>
          <cover-view class="legend-item">
            <cover-view class="legend-color factory"></cover-view>
            <cover-text class="legend-text">化工厂</cover-text>
          </cover-view>
        </cover-view>
      </map>
      <!-- #endif -->
      </view>

    <!-- 设备列表和预测控制面板 -->
    <view class="control-panel">
      <view class="panel-header">
        <text class="panel-title">设备监测与污染预测</text>
        <view class="panel-controls">
          <!-- AI服务开关 -->
          <view class="ai-service-toggle" @click="toggleAIService">
            <uni-icons :type="useAIService ? 'light' : 'circle'" size="16" :color="useAIService ? '#4CAF50' : '#999'"></uni-icons>
            <text class="toggle-text" :class="{ 'active': useAIService }">{{ useAIService ? 'AI智能' : '规则分析' }}</text>
        </view>
      </view>
        <view class="legend">
          <view class="legend-item">
            <view class="legend-dot online"></view>
            <text class="legend-text">在线</text>
        </view>
          <view class="legend-item">
            <view class="legend-dot offline"></view>
            <text class="legend-text">离线</text>
      </view>
          <view class="legend-item">
            <view class="legend-dot fault"></view>
            <text class="legend-text">故障</text>
        </view>
          <view class="legend-item">
            <view class="legend-dot factory"></view>
            <text class="legend-text">化工厂</text>
      </view>
        </view>
      </view>
      <view class="update-hint">数据每分钟自动更新 · 最近：{{ lastUpdated || '—' }}</view>
      
      <!-- 设备列表 -->
      <scroll-view scroll-y class="device-list">
        <view class="device-item" :class="{ 'fault-device': device.status === 'fault' }" v-for="device in deviceList" :key="device.id" @click="selectDevice(device)">
          <view class="device-info">
            <view class="device-header">
              <text class="device-name" :class="{ 'fault-name': device.status === 'fault' }">{{ device.name }}</text>
              <text class="status-text" :class="{ 'fault-status': device.status === 'fault' }">{{ getStatusText(device.status) }}</text>
              <view class="device-status" :class="device.status"></view>
        </view>
            <text class="device-location" :class="{ 'fault-location': device.status === 'fault' }">{{ device.location }}</text>
            <view class="device-data">
              <text class="data-item" :class="{ 'fault-data-item': isPhFault(device.ph) }">pH: {{ device.ph }}</text>
              <text class="data-item" :class="{ 'fault-data-item': isTempFault(device.temp) }">温度: {{ device.temp }}°C</text>
              <text class="data-item" :class="{ 'fault-data-item': isNtuFault(device.ntu) }">浊度: {{ device.ntu }} NTU</text>
            </view>
            <!-- 预测按钮 -->
            <button class="predict-btn" @click.stop="startPollutionPrediction(device)" :disabled="isAnalyzing">
              {{ isAnalyzing ? '分析中...' : 'AI预测' }}
            </button>
          </view>
          <uni-icons type="right" size="16" :color="device.status === 'fault' ? '#ff4444' : '#ccc'"></uni-icons>
        </view>
      </scroll-view>
      </view>

    <!-- 底部统计 -->
    <view class="bottom-stats">
      <view class="stat-item">
        <text class="stat-number">{{ stats?.total || 0 }}</text>
        <text class="stat-label">总设备</text>
        </view>
      <view class="stat-item">
        <text class="stat-number online">{{ stats?.online || 0 }}</text>
        <text class="stat-label">在线</text>
      </view>
      <view class="stat-item">
        <text class="stat-number offline">{{ stats?.offline || 0 }}</text>
        <text class="stat-label">离线</text>
      </view>
      <view class="stat-item">
        <text class="stat-number fault">{{ stats?.fault || 0 }}</text>
        <text class="stat-label">故障</text>
      </view>
    </view>

    <!-- 污染预测结果弹窗 -->
    <view class="prediction-modal" v-if="showPredictionModal" @click="closePredictionModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">污染预测分析结果</text>
          <text class="close-btn" @click="closePredictionModal">×</text>
      </view>
      
        <view class="modal-body">
          <!-- 设备信息 -->
          <view class="device-info-section" v-if="selectedDevice">
            <text class="section-title">监测设备信息</text>
            <view class="info-item">
              <text class="info-label">设备名称：</text>
              <text class="info-value">{{ selectedDevice.name }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">位置：</text>
              <text class="info-value">{{ selectedDevice.location }}</text>
        </view>
            <view class="info-item">
              <text class="info-label">坐标：</text>
              <text class="info-value">{{ selectedDevice.latitude }}, {{ selectedDevice.longitude }}</text>
            </view>
        </view>
        
          <!-- 附近化工厂分析 -->
          <view class="factory-analysis-section" v-if="predictionResult?.nearbyFactories">
            <text class="section-title">附近化工厂分析</text>
            <view class="factory-list">
              <view class="factory-item" v-for="factory in predictionResult.nearbyFactories" :key="factory.id">
                <view class="factory-header">
                  <text class="factory-name">{{ factory.name }}</text>
                  <text class="factory-distance">{{ factory.distance }}km</text>
            </view>
                <view class="factory-details">
                  <text class="factory-industry">行业：{{ factory.industry }}</text>
                  <text class="factory-pollutants">主要污染物：{{ factory.mainPollutants }}</text>
                  <text class="factory-risk" :class="factory.riskLevel">风险等级：{{ factory.riskLevel }}</text>
                </view>
              </view>
      </view>
        </view>
        
          <!-- 污染状态 -->
          <view class="pollution-status-section" v-if="predictionResult?.isPolluted !== undefined">
            <text class="section-title">污染检测状态</text>
            <view class="pollution-status" :class="{ 'polluted': predictionResult.isPolluted, 'normal': !predictionResult.isPolluted }">
              <uni-icons :type="predictionResult.isPolluted ? 'fire' : 'checkmarkempty'" size="20" :color="predictionResult.isPolluted ? '#ff4444' : '#4cd964'"></uni-icons>
              <text>{{ predictionResult.isPolluted ? '检测到污染' : '水质正常' }}</text>
      </view>
    </view>

          <!-- 污染源分析 -->
          <view class="pollution-source-section" v-if="predictionResult?.pollutionSourceAnalysis?.suspectedFactories?.length > 0">
            <text class="section-title">可疑污染源</text>
            <view class="suspected-factories">
              <view class="factory-item suspected" v-for="(factory, index) in predictionResult.pollutionSourceAnalysis.suspectedFactories" :key="factory.factoryId">
                <view class="factory-header">
                  <text class="factory-name">{{ factory.factoryName }}</text>
                  <text class="pollution-probability">{{ factory.pollutionProbability }}%</text>
                </view>
                <view class="factory-details">
                  <text class="factory-distance">距离: {{ factory.distance }}km</text>
                  <text class="factory-risk" :class="factory.riskLevel">{{ factory.riskLevel }}</text>
                </view>
                <view class="pollution-reason">{{ factory.reason }}</view>
              </view>
            </view>
      </view>
      
          <!-- 污染预测结果 -->
          <view class="prediction-result-section" v-if="predictionResult?.prediction">
            <text class="section-title">污染预测结果</text>
            <view class="prediction-content">
              <text class="prediction-text">{{ predictionResult.prediction }}</text>
            </view>
          </view>
      
          <!-- 建议措施 -->
          <view class="recommendations-section" v-if="predictionResult?.recommendations">
            <text class="section-title">建议措施</text>
            <view class="recommendations-list">
              <text class="recommendation-item" v-for="(rec, index) in predictionResult.recommendations" :key="index">
                {{ index + 1 }}. {{ rec }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import { useDeviceStore } from '@/stores/device.js'
import { getLatestRedisData } from '@/api/waterQuality.js'
import { pollutionApi } from '@/api/pollution.js'
import { TENCENT_MAP_CONFIG } from '@/config/tencent-map.js'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

const deviceStore = useDeviceStore()

// 地图相关状态
const isMapFullscreen = ref(false)
const mapConfig = ref(TENCENT_MAP_CONFIG)
const qqmapsdk = ref({})
const userLocation = ref({
  latitude: 38.814788,
  longitude: 115.489120,
  address: ''
})

// 监测指标正常范围
const NORMAL_RANGE = {
  ph: { min: 6.5, max: 8.5 },
  temp: { min: 20, max: 30 },
  ntu: { min: 0, max: 3000 }
}

// 真实数据监测点ID
const REAL_DEVICE_ID = "ESP8266_001"

// 监测点001的真实数据对象
const realDeviceData = ref({
  id: "ESP8266_001",
  name: "监测点001",
  location: "河北省保定市莲池区博学路",
  latitude: 38.814788,
  longitude: 115.489120,
  ph: 7.12,
  temp: 28,
  ntu: 0,
  status: "online"
})

// 设备列表 - 从数据库动态加载
const deviceList = ref([])

// 加载设备数据
async function loadDeviceData() {
  try {
    console.log('开始从后端加载设备数据...')

    // 调用后端API获取设备列表
    const res = await pollutionApi.getDeviceList()

    if (res.code === 200 && res.obj?.devices) {
      // 将后端返回的数据转换为前端所需格式
      deviceList.value = res.obj.devices.map(device => ({
        id: device.id,
        name: device.name,
        location: device.location || '待获取地址',
        status: device.status,
        ph: device.ph,
        temp: device.temp,
        ntu: device.ntu,
        longitude: device.longitude,
        latitude: device.latitude
      }))

      // 将真实设备数据（从Redis获取）放在第一个位置
      const realDeviceIndex = deviceList.value.findIndex(d => d.id === REAL_DEVICE_ID)
      if (realDeviceIndex >= 0) {
        const realDevice = deviceList.value.splice(realDeviceIndex, 1)[0]
        deviceList.value.unshift(realDevice)
      }

      console.log('设备数据加载完成，共', deviceList.value.length, '个设备')
      console.log('设备列表:', deviceList.value)

      // 更新统计数据
      updateStats()

      // 如果有设备数据，更新地图中心到第一个设备的位置
      if (deviceList.value.length > 0) {
        const firstDevice = deviceList.value[0]
        updateMapCenter(firstDevice.longitude, firstDevice.latitude)
      }
    } else {
      console.warn('后端返回设备数据格式错误，使用默认设备数据')
      throw new Error('设备数据格式错误')
    }

  } catch (error) {
    console.error('从后端加载设备数据失败:', error)

    // 失败时使用默认设备数据
    console.log('使用本地默认设备数据')
    deviceList.value = [
      realDeviceData.value,
      {
        id: 2,
        name: '监测点002',
        location: '待获取地址',
        status: 'online',
        ph: 7.2,
        temp: 22.5,
        ntu: 1200,
        longitude: 116.357428,
        latitude: 38.814788
      },
      {
        id: 3,
        name: '监测点003',
        location: '待获取地址',
        status: 'online',
        ph: 6.8,
        temp: 24.2,
        ntu: 1800,
        longitude: 116.437428,
        latitude: 39.92923
      },
      {
        id: 4,
        name: '监测点004',
        location: '待获取地址',
        status: 'online',
        ph: 7.5,
        temp: 21.3,
        ntu: 900,
        longitude: 116.317428,
        latitude: 39.88923
      },
      {
        id: 5,
        name: '监测点005',
        location: '待获取地址',
        status: 'online',
        ph: 6.9,
        temp: 23.7,
        ntu: 1500,
        longitude: 116.277428,
        latitude: 39.86923
      },
      {
        id: 6,
        name: '监测点006',
        location: '待获取地址',
        status: 'online',
        ph: 7.3,
        temp: 22.1,
        ntu: 1100,
        longitude: 116.195428,
        latitude: 39.91323
      },
      {
        id: 7,
        name: '监测点007',
        location: '待获取地址',
        status: 'online',
        ph: 7.1,
        temp: 23.8,
        ntu: 1600,
        longitude: 116.661428,
        latitude: 39.90923
      },
      {
        id: 8,
        name: '监测点008',
        location: '待获取地址',
        status: 'online',
        ph: 6.7,
        temp: 25.1,
        ntu: 2000,
        longitude: 116.235428,
        latitude: 40.22423
      }
    ]

    updateStats()
    console.log('使用默认设备数据，共', deviceList.value.length, '个设备')
  }
}

const stats = ref({
  total: 0,
  online: 0,
  offline: 0,
  fault: 0
})

const lastUpdated = ref('')

// 污染预测相关状态
const isAnalyzing = ref(false)
const showPredictionModal = ref(false)
const selectedDevice = ref(null)
const predictionResult = ref(null)

// AI服务设置
const useAIService = ref(true) // 控制是否使用AI服务

// 附近化工厂数据（模拟数据）
const nearbyFactories = ref([
  {
    id: 1,
    name: '保定化工厂A',
    latitude: 38.824788,
    longitude: 115.499120,
    industry: '化工制造',
    mainPollutants: 'SO2, NOx, PM2.5',
    riskLevel: 'high',
    distance: 1.2
  },
  {
    id: 2,
    name: '华北石化B',
    latitude: 38.804788,
    longitude: 115.479120,
    industry: '石油化工',
    mainPollutants: 'VOCs, CO, H2S',
    riskLevel: 'medium',
    distance: 2.1
  },
  {
    id: 3,
    name: '环保材料厂C',
    latitude: 38.834788,
    longitude: 115.509120,
    industry: '新材料',
    mainPollutants: '粉尘, 有机废气',
    riskLevel: 'low',
    distance: 0.8
  }
])

// 地图标记点
const markers = computed(() => {
  const deviceMarkers = deviceList.value.map((device, index) => ({
    id: device.id,
    latitude: device.latitude,
    longitude: device.longitude,
    title: device.name,
    width: 20,
    height: 20,
    iconPath: getMarkerIcon(device.id),
    callout: {
      content: `${device.name}\n${device.location}\n状态: ${getStatusText(device.status)}\n pH: ${device.ph}  温度: ${device.temp}°C  浊度: ${device.ntu}NTU`,
      color: '#333',
      fontSize: 12,
      borderRadius: 4,
      bgColor: '#fff',
      padding: 8,
      display: 'BYCLICK'
    }
  }))
  
  // 添加化工厂标记
  const factoryMarkers = nearbyFactories.value.map(factory => ({
    id: `factory_${factory.id}`,
    latitude: factory.latitude,
    longitude: factory.longitude,
    title: factory.name,
    width: 24,
    height: 24,
    iconPath: '/static/images/marker-factory.png',
    callout: {
      content: `${factory.name}\n行业: ${factory.industry}\n主要污染物: ${factory.mainPollutants}\n风险等级: ${factory.riskLevel}`,
      color: '#333',
      fontSize: 12,
      borderRadius: 4,
      bgColor: '#fff',
      padding: 8,
      display: 'BYCLICK'
    }
  }))
  
  return [...deviceMarkers, ...factoryMarkers]
})

// 地图相关方法
const toggleMapFullscreen = () => {
  isMapFullscreen.value = !isMapFullscreen.value
  // H5下切换尺寸后，触发一次重绘和中心复位
  // #ifdef H5
  setTimeout(() => {
    if (window.h5MapInstance && window.qq?.maps) {
      const center = new window.qq.maps.LatLng(
        mapConfig.value.center[1],
        mapConfig.value.center[0]
      )
      window.qq.maps.event.trigger(window.h5MapInstance, 'resize')
      window.h5MapInstance.setCenter(center)
    }
  }, 300)
  // #endif
}

const requestLocation = () => {
  console.log('用户手动请求定位')
  uni.showLoading({ title: '正在定位...' })
  
  const closeLoading = () => {
    if (uni.getStorageSync('locationLoading')) {
      uni.hideLoading()
      uni.removeStorageSync('locationLoading')
    }
  }
  uni.setStorageSync('locationLoading', true)
  
  const loadingTimer = setTimeout(closeLoading, 12000)
  
  getUserLocation({
    onComplete: () => {
      clearTimeout(loadingTimer)
      closeLoading()
    }
  })
}

const getUserLocation = (options = {}) => {
  console.log('定位到固定坐标')
  
          uni.showToast({
    title: '定位成功',
    icon: 'success',
    duration: 2000
  })
  
  userLocation.value = {
    latitude: 38.814788,
    longitude: 115.489120,
    address: '固定位置 (115.489120, 38.814788)'
  }
  
  updateMapCenter(
    userLocation.value.longitude,
    userLocation.value.latitude
  )
  
  console.log('定位到固定坐标完成:', userLocation.value)
  
  options.onComplete?.()
}

const updateMapCenter = (longitude, latitude) => {
  // #ifdef H5
  if (window.qq && window.qq.maps && window.h5MapInstance) {
    try {
      const lat = parseFloat(latitude)
      const lng = parseFloat(longitude)
      
      if (isNaN(lat) || isNaN(lng)) {
        console.error('H5 - 无效的坐标值:', { latitude, longitude })
        return
      }
      
      if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
        console.error('H5 - 坐标超出有效范围:', { lat, lng })
        return
      }
      
      const newCenter = new window.qq.maps.LatLng(lat, lng)
      window.h5MapInstance.setCenter(newCenter)
      console.log('H5 - 地图中心点已更新到用户位置')
      
    } catch (error) {
      console.error('H5 - 更新地图中心失败:', error)
    }
  }
  // #endif
  
  // #ifdef MP-WEIXIN
  const lat = parseFloat(latitude)
  const lng = parseFloat(longitude)
  
  if (isNaN(lat) || isNaN(lng)) {
    console.error('小程序 - 无效的坐标值:', { latitude, longitude })
    return
  }
  
  if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
    console.error('小程序 - 坐标超出有效范围:', { lat, lng })
    return
  }
  
  mapConfig.value.center = [lng, lat]
  console.log('小程序 - 地图中心点已更新:', mapConfig.value.center)
  // #endif
}

const getMarkerIcon = (deviceId) => {
  const device = deviceList.value.find(d => d.id === deviceId)
  if (device) {
    switch(device.status) {
      case 'online':
        return '/static/images/marker-online.png'
      case 'offline':
        return '/static/images/marker-offline.png'
      case 'fault':
        return '/static/images/marker-fault.png'
    }
  }
  return 'https://mapapi.qq.com/webapi/staticimage/v2?size=20x20&color=FF0000&format=png'
}

const onMarkerTap = (e) => {
  const markerId = e.detail.markerId
  const device = deviceList.value.find(d => d.id === markerId)
  if (device) {
    selectDevice(device)
  }
}

const onRegionChange = (e) => {
  console.log('地图区域变化:', e.detail)
}

const onMapUpdated = (e) => {
  console.log('地图更新:', e)
  if (e.detail && e.detail.scale) {
    mapConfig.value.zoom = e.detail.scale
    console.log('地图缩放级别更新为:', e.detail.scale)
  }
}

const onMapTap = (e) => {
  console.log('地图点击:', e.detail)
}

const selectDevice = (device) => {
  console.log('选择设备:', device.name)
  
  updateMapCenter(device.longitude, device.latitude)
  
        uni.showToast({
    title: `已定位到${device.name}`,
    icon: 'success',
    duration: 2000
  })
}

// 污染预测相关方法
const startPollutionPrediction = async (device) => {
  if (isAnalyzing.value) return
  
  try {
    isAnalyzing.value = true
    selectedDevice.value = device
    
    uni.showLoading({ title: 'AI分析中...' })
    
    // 构建位置数据
    const locationData = {
      latitude: device.latitude,
      longitude: device.longitude,
      deviceId: device.id,
      deviceName: device.name,
      currentData: {
        ph: device.ph,
        temp: device.temp,
        ntu: device.ntu,
        status: device.status
      },
      useAIService: useAIService.value, // 添加AI服务开关
      timestamp: new Date().toISOString()
    }
    
    // 调用新的基于位置的污染预测接口
    const res = await pollutionApi.analyzeByLocation(locationData)
        
        if (res.code === 200) {
      // 处理分析结果
      const prediction = res.obj?.prediction || generateMockPrediction(device)
      predictionResult.value = {
        nearbyFactories: res.obj?.nearbyFactories || [],
        isPolluted: res.obj?.isPolluted || false,
        pollutionSourceAnalysis: res.obj?.pollutionSourceAnalysis || {},
        prediction: prediction,
        recommendations: res.obj?.recommendations || generateMockRecommendations(device)
      }

      // 检查是否是AI生成的内容（真正的AI结果通常更专业、更详细）
      const isAIGenerated = isAIGeneratedContent(prediction)
      const isRuleAnalysis = prediction.includes('基于设备位置的污染预测分析') && !isAIGenerated
      
      showPredictionModal.value = true

          // 根据分析类型显示不同提示
          let toastTitle = '分析完成'
          if (isAIGenerated) {
            toastTitle = 'AI智能分析完成'
          } else if (isRuleAnalysis) {
            toastTitle = '规则分析完成（AI服务暂时不可用）'
        } else {
            toastTitle = '分析完成'
          }

          uni.showToast({
            title: toastTitle,
            icon: 'success'
          })
        } else {
      // 使用模拟数据
      predictionResult.value = {
        nearbyFactories: nearbyFactories.value.map(factory => ({
          ...factory,
          distance: calculateDistance(
            device.latitude, device.longitude,
            factory.latitude, factory.longitude
          )
        })),
        prediction: generateMockPrediction(device),
        recommendations: generateMockRecommendations(device)
      }
      
      showPredictionModal.value = true
      
          uni.showToast({
        title: '分析完成（模拟数据）',
        icon: 'success'
          })
        }
      } catch (error) {
    console.error('污染预测分析失败:', error)
    
    // 使用模拟数据作为备选
    predictionResult.value = {
      nearbyFactories: nearbyFactories.value.map(factory => ({
        ...factory,
        distance: calculateDistance(
          device.latitude, device.longitude,
          factory.latitude, factory.longitude
        )
      })),
      prediction: generateMockPrediction(device),
      recommendations: generateMockRecommendations(device)
    }
    
    showPredictionModal.value = true
    
        uni.showToast({
      title: '分析完成（离线模式）',
      icon: 'success'
        })
      } finally {
    isAnalyzing.value = false
        uni.hideLoading()
      }
}

const closePredictionModal = () => {
  showPredictionModal.value = false
  selectedDevice.value = null
  predictionResult.value = null
}

// 工具方法
const calculateDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371 // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLon = (lon2 - lon1) * Math.PI / 180
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  return (R * c).toFixed(1)
}

const generateMockPrediction = (device) => {
  const riskLevel = device.status === 'fault' ? '高' : '中'
  return `基于设备${device.name}的监测数据，AI分析显示当前区域存在${riskLevel}风险。附近化工厂可能对水质造成影响，建议加强监测频率。`
}

const generateMockRecommendations = (device) => {
  return [
    '增加监测频率，每15分钟采集一次数据',
    '检查附近化工厂的排放情况',
    '如发现异常，立即启动应急预案',
    '通知相关部门进行现场核查'
  ]
}

const getStatusText = (status) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    fault: '故障'
  }
  return statusMap[status] || '未知'
}

const isPhFault = (ph) => {
  return ph < NORMAL_RANGE.ph.min || ph > NORMAL_RANGE.ph.max
}

const isTempFault = (temp) => {
  return temp < NORMAL_RANGE.temp.min || temp > NORMAL_RANGE.temp.max
}

const isNtuFault = (ntu) => {
  return ntu < NORMAL_RANGE.ntu.min || ntu > NORMAL_RANGE.ntu.max
}

const updateStats = () => {
  const total = deviceList.value.length
  let online = 0, fault = 0, offline = 0
  deviceList.value.forEach(d => {
    if (d.status === 'online') online++
    else if (d.status === 'fault') fault++
    else offline++
  })
  stats.value = { total, online, offline, fault }
}

// 模拟数据更新
let simulateTimer = null

const simulateOnce = () => {
  deviceList.value = deviceList.value.map(d => {
    if (d.id === REAL_DEVICE_ID) {
      return d
    }
    
    let nextPh, nextTemp, nextNtu
    
    if (Math.random() < 0.3) {
      nextPh = Math.random() * 6 + 2
    } else {
      nextPh = Math.random() * 4 + 5.5
    }
    
    if (Math.random() < 0.25) {
      nextTemp = Math.random() * 40 + 0
    } else {
      nextTemp = Math.random() * 20 + 10
    }
    
    if (Math.random() < 0.35) {
      nextNtu = Math.random() * 8000 + 1000
    } else {
      nextNtu = Math.random() * 3000 + 0
    }
    
    const newStatus = (nextPh >= NORMAL_RANGE.ph.min && nextPh <= NORMAL_RANGE.ph.max &&
                      nextTemp >= NORMAL_RANGE.temp.min && nextTemp <= NORMAL_RANGE.temp.max &&
                      nextNtu >= NORMAL_RANGE.ntu.min && nextNtu <= NORMAL_RANGE.ntu.max) ? 'online' : 'fault'
    
    return { 
      ...d, 
      ph: +nextPh.toFixed(2), 
      temp: +nextTemp.toFixed(1), 
      ntu: Math.round(nextNtu), 
      status: newStatus 
    }
  })
  updateStats()
  
  const pad = (n) => (n < 10 ? '0' + n : '' + n)
  const now = new Date()
  lastUpdated.value = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
}

function startSimulateTimer() {
  if (simulateTimer) return
  simulateOnce()
  simulateTimer = setInterval(simulateOnce, 30 * 1000)
}

function stopSimulateTimer() {
  if (simulateTimer) {
    clearInterval(simulateTimer)
    simulateTimer = null
  }
}

// 真实数据更新
let realDataTimer = null

async function fetchRealDeviceLatest() {
  try {
    const deviceId = REAL_DEVICE_ID
    const res = await getLatestRedisData(deviceId)
    if (res && res.code === 200 && res.obj) {
      const d = res.obj
      if (typeof d.ph === 'number') realDeviceData.value.ph = +d.ph
      if (typeof d.temp === 'number') realDeviceData.value.temp = +d.temp
      if (typeof d.ntu === 'number') realDeviceData.value.ntu = Math.round(d.ntu)
      if (d.status) realDeviceData.value.status = d.status
      else realDeviceData.value.status = (d.ph >= NORMAL_RANGE.ph.min && d.ph <= NORMAL_RANGE.ph.max &&
                                          d.temp >= NORMAL_RANGE.temp.min && d.temp <= NORMAL_RANGE.temp.max &&
                                          d.ntu >= NORMAL_RANGE.ntu.min && d.ntu <= NORMAL_RANGE.ntu.max) ? 'online' : 'fault'
      if (d.latitude && d.longitude) {
        realDeviceData.value.latitude = d.latitude
        realDeviceData.value.longitude = d.longitude
      }
      if (d.location) realDeviceData.value.location = d.location
      
      deviceList.value[0] = { ...realDeviceData.value }
      updateStats()
    }
  } catch (e) {
    console.error('获取真实数据失败:', e)
  }
}

function startRealDataTimer() {
  if (realDataTimer) clearInterval(realDataTimer)
  realDataTimer = setInterval(() => {
    fetchRealDeviceLatest()
  }, 10000)
}

function stopRealDataTimer() {
  if (realDataTimer) {
    clearInterval(realDataTimer)
    realDataTimer = null
  }
}

// 加载附近化工厂数据
async function loadNearbyFactories() {
  try {
    console.log('开始加载附近化工厂数据')
    
    // 使用第一个设备的坐标作为中心点
    const centerDevice = deviceList.value[0]
    if (centerDevice && centerDevice.latitude && centerDevice.longitude) {
      const res = await pollutionApi.getNearbyFactories(
        centerDevice.latitude, 
        centerDevice.longitude, 
        15 // 15公里范围
      )
      
      if (res.code === 200 && res.obj?.factories) {
        // 更新化工厂数据
        nearbyFactories.value = res.obj.factories.map(factory => ({
          id: factory.id,
          name: factory.name,
          latitude: factory.latitude,
          longitude: factory.longitude,
          industry: factory.industry,
          mainPollutants: factory.mainPollutants,
          riskLevel: factory.riskLevel,
          distance: factory.distance
        }))
        
        console.log('成功加载化工厂数据:', nearbyFactories.value.length, '家')
        
        // 更新地图标记
        updateMapMarkers()
      } else {
        console.log('使用模拟化工厂数据')
      }
    }
  } catch (error) {
    console.error('加载化工厂数据失败:', error)
    console.log('使用模拟化工厂数据')
  }
}

// 更新地图标记
function updateMapMarkers() {
  // #ifdef H5
  if (window.h5MapInstance && window.h5MarkersById) {
    // 清除现有化工厂标记
    Object.keys(window.h5MarkersById).forEach(key => {
      if (key.startsWith('factory_')) {
        window.h5MarkersById[key].setMap(null)
        delete window.h5MarkersById[key]
      }
    })
    
    // 添加新的化工厂标记
    nearbyFactories.value.forEach(factory => {
      const position = new window.qq.maps.LatLng(factory.latitude, factory.longitude)
      const marker = new window.qq.maps.Marker({
        position,
        map: window.h5MapInstance,
        title: factory.name
      })
      
      const iconUrl = buildFactorySvgDataUrl(factory.riskLevel)
      const size = new window.qq.maps.Size(24, 24)
      const markerImage = new window.qq.maps.MarkerImage(iconUrl, null, null, null, size)
      marker.setIcon(markerImage)
      
      // 绑定点击事件
      window.qq.maps.event.addListener(marker, 'click', () => {
        const html = `<div style="min-width:200px;line-height:1.6;">
          <div style="font-weight:600;margin-bottom:8px;">${factory.name}</div>
          <div>行业：${factory.industry}</div>
          <div>主要污染物：${factory.mainPollutants}</div>
          <div>风险等级：<span style="color: ${getRiskColor(factory.riskLevel)};font-weight:bold;">${factory.riskLevel}</span></div>
          <div>距离：${factory.distance}km</div>
        </div>`
        
        if (window.h5InfoWindow) {
          window.h5InfoWindow.setContent(html)
          window.h5InfoWindow.setPosition(position)
          window.h5InfoWindow.open()
        }
      })
      
      window.h5MarkersById[`factory_${factory.id}`] = marker
    })
    
    console.log('H5地图化工厂标记更新完成')
  }
  // #endif
}

// 获取风险等级对应的颜色
function getRiskColor(riskLevel) {
  switch (riskLevel) {
    case 'high': return '#ff4444'
    case 'medium': return '#ffa500'
    case 'low': return '#4cd964'
    default: return '#999999'
  }
}

// 切换AI服务状态
function toggleAIService() {
  useAIService.value = !useAIService.value
  console.log('AI服务状态切换为:', useAIService.value ? '启用' : '禁用')

        uni.showToast({
    title: useAIService.value ? '已启用AI智能分析' : '已切换到规则分析',
    icon: 'success',
    duration: 1500
  })
}

// 判断内容是否由AI生成
function isAIGeneratedContent(content) {
  if (!content || typeof content !== 'string') return false

  // AI生成的内容特征：
  // 1. 通常包含更专业的术语和结构化的分析
  // 2. 包含多个段落和详细的解释
  // 3. 使用更正式的语言和专业的表述
  // 4. 包含具体的科学依据或分析方法

  const aiIndicators = [
    '基于环境科学和污染控制专业知识',
    '水质状况综合评估',
    '污染扩散趋势预测',
    '应急响应建议',
    '长期监测建议',
    '影响评估',
    '风险等级建议',
    '监测数据分析',
    '污染物扩散模型',
    '环境风险评估',
    '化工厂环境影响分析',
    '污染风险评估',
    '污染物扩散可能性分析',
    '周边水体和居民的影响评估',
    '优先监测建议',
    '应急响应措施建议',
    '长期环境监测规划'
  ]

  const lowerContent = content.toLowerCase()
  const indicatorsFound = aiIndicators.filter(indicator =>
    lowerContent.includes(indicator.toLowerCase())
  ).length

  // 如果找到2个或以上的AI特征词，认为是由AI生成的
  return indicatorsFound >= 2
}

// 地图初始化
function initTencentMap() {
  // #ifdef MP-WEIXIN
  try {
    const QQMapWX = require('../../common/lib/qqmap-wx-jssdk.min.js')
    const mapKey = mapConfig.value.key
    if (!mapKey) {
      console.error('腾讯地图 Key 未配置，请检查 @/config/tencent-map.js')
      uni.showToast({ title: '地图Key未配置', icon: 'none' })
        return
      }
    qqmapsdk.value = new QQMapWX({ key: mapKey })
    console.log('小程序 - 腾讯地图 SDK 初始化成功')
    
    getUserLocation()
  } catch (error) {
    console.error('小程序 - 地图 SDK 加载失败:', error)
    uni.showToast({ title: '地图加载失败', icon: 'none' })
  }
  // #endif

  // #ifdef H5
  console.log('H5 环境 - 加载腾讯地图 SDK 脚本')
  
  const oldScript = document.querySelector('script[src*="map.qq.com/api/js"]')
  if (oldScript) oldScript.remove()
  if (window.initTencentMapH5) delete window.initTencentMapH5

  const script = document.createElement('script')
  script.src = `https://map.qq.com/api/js?v=2.exp&key=${mapConfig.value.key}&callback=initTencentMapH5&libraries=geometry`
  script.onerror = () => {
    console.error('H5 - 地图 SDK 加载失败')
    uni.showToast({ title: 'H5地图加载失败', icon: 'none' })
  }
  
  window.initTencentMapH5 = () => {
    if (window.h5MapInstance) {
      console.log('H5 - 地图已初始化，跳过重复创建')
      getUserLocation()
      return
    }
    console.log('H5 - 腾讯地图 SDK 加载成功')
    initMapForH5()
    getUserLocation()
  }
  
  document.body.appendChild(script)
  // #endif
}

function initMapForH5() {
  if (!window.qq || !window.qq.maps) {
    console.error('H5 - 地图 SDK 未加载完成')
    return
  }

  let retryCount = 0
  const getMapContainer = () => {
    const mapContainer = document.getElementById('tencentMap')
    if (mapContainer) {
      initMapInstance(mapContainer)
    } else if (retryCount < 3) {
      retryCount++
      setTimeout(getMapContainer, 500)
      console.log(`H5 - 重试获取地图容器（${retryCount}/3）`)
    } else {
      console.error('H5 - 多次重试仍未找到地图容器')
    }
  }

  const initMapInstance = (mapContainer) => {
    try {
      const center = new window.qq.maps.LatLng(
        mapConfig.value.center[1],
        mapConfig.value.center[0]
      )
      window.h5MapInstance = new window.qq.maps.Map(mapContainer, {
        center: center,
        zoom: mapConfig.value.zoom || 10,
        disableDefaultUI: false,
        zoomControl: true,
        scrollwheel: true,
        disableDoubleClickZoom: false,
        gestureHandling: 'auto'
      })
      console.log('H5 - 地图初始化成功')
      
      // 添加标记点
      if (!window.h5MarkersById) window.h5MarkersById = {}
      
      // 设备标记
      deviceList.value.forEach(device => {
        const position = new window.qq.maps.LatLng(device.latitude, device.longitude)
        const marker = new window.qq.maps.Marker({
          position,
          map: window.h5MapInstance,
          title: device.name
        })
        
        const color = getStatusColor(device.status)
        const iconUrl = buildStatusSvgDataUrl(color, device.status)
        const size = new window.qq.maps.Size(24, 24)
        const markerImage = new window.qq.maps.MarkerImage(iconUrl, null, null, null, size)
        marker.setIcon(markerImage)
        
        window.qq.maps.event.addListener(marker, 'click', () => {
          selectDevice(device)
        })
        
        window.h5MarkersById[device.id] = marker
      })
      
      // 化工厂标记
      nearbyFactories.value.forEach(factory => {
        const position = new window.qq.maps.LatLng(factory.latitude, factory.longitude)
        const marker = new window.qq.maps.Marker({
          position,
          map: window.h5MapInstance,
          title: factory.name
        })
        
        const iconUrl = buildFactorySvgDataUrl(factory.riskLevel)
        const size = new window.qq.maps.Size(24, 24)
        const markerImage = new window.qq.maps.MarkerImage(iconUrl, null, null, null, size)
        marker.setIcon(markerImage)
        
        window.h5MarkersById[`factory_${factory.id}`] = marker
      })
      
    } catch (error) {
      console.error('H5 - 地图初始化失败:', error)
    }
  }

  getMapContainer()
}

const getStatusColor = (status) => {
  if (status === 'online') return '#4cd964'
  if (status === 'fault') return '#dd524d'
  return '#999999'
}

const buildStatusSvgDataUrl = (color, status = 'online') => {
  let svg
  if (status === 'fault') {
    svg = `<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
      <circle cx='12' cy='12' r='10' fill='${color}' stroke='#ff0000' stroke-width='2' />
      <circle cx='12' cy='12' r='6' fill='white' opacity='0.9' />
      <text x='12' y='16' text-anchor='middle' font-family='Arial' font-size='12' font-weight='bold' fill='#ff0000'>!</text>
    </svg>`
        } else {
    svg = `<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
      <circle cx='12' cy='12' r='10' fill='${color}' />
      <circle cx='12' cy='12' r='4' fill='white' opacity='0.2' />
    </svg>`
  }
  return 'data:image/svg+xml;utf8,' + encodeURIComponent(svg)
}

const buildFactorySvgDataUrl = (riskLevel) => {
  let color = '#ffa500' // 默认橙色
  if (riskLevel === 'high') color = '#ff4444'
  else if (riskLevel === 'medium') color = '#ffa500'
  else if (riskLevel === 'low') color = '#4cd964'
  
  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
    <rect x='4' y='8' width='16' height='12' fill='${color}' stroke='#333' stroke-width='1' />
    <rect x='6' y='10' width='2' height='2' fill='white' />
    <rect x='10' y='10' width='2' height='2' fill='white' />
    <rect x='14' y='10' width='2' height='2' fill='white' />
    <rect x='6' y='14' width='2' height='2' fill='white' />
    <rect x='10' y='14' width='2' height='2' fill='white' />
    <rect x='14' y='14' width='2' height='2' fill='white' />
    <rect x='10' y='4' width='4' height='4' fill='${color}' stroke='#333' stroke-width='1' />
  </svg>`
  return 'data:image/svg+xml;utf8,' + encodeURIComponent(svg)
}

// 生命周期
onMounted(async () => {
  console.log('污染预测页面加载完成')

  if (!mapConfig.value || !mapConfig.value.key) {
    console.error('错误：腾讯地图Key未配置，请检查 @/config/tencent-map.js')
    uni.showModal({
      title: '配置错误',
      content: '腾讯地图Key未配置，地图功能无法使用',
      showCancel: false
    })
    return
  }

  const keyLength = mapConfig.value.key.length
  const isValidFormat = keyLength === 32 || (keyLength === 35 && mapConfig.value.key.includes('-'))
  if (!isValidFormat) {
    console.error('错误：腾讯地图Key格式无效（应为32位字符串或35位带连字符格式）')
    uni.showModal({
      title: 'Key无效',
      content: '当前腾讯地图Key格式错误，请检查配置',
      showCancel: false
    })
    return
  }

  // 加载设备数据
  await loadDeviceData()

  console.log('设备列表:', deviceList.value)
  console.log('统计数据:', stats.value)
  console.log('地图配置:', mapConfig.value)
  console.log('当前使用的 Key:', mapConfig.value.key)

  initTencentMap()
  fetchRealDeviceLatest()
  loadNearbyFactories()
})

onUnmounted(() => {
  stopSimulateTimer()
  stopRealDataTimer()
})

onShow(() => {
  console.log('污染预测页面显示，立即获取数据并启动定时器')
  fetchRealDeviceLatest()
  startSimulateTimer()
  startRealDataTimer()
})

onHide(() => {
  console.log('污染预测页面隐藏，停止定时器')
  stopSimulateTimer()
  stopRealDataTimer()
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  text-align: center;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 0 0 20rpx 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  display: block;
  margin-bottom: 8rpx;
}

.subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  display: block;
}

/* 地图容器样式 */
.map-container {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin: 0 20rpx 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  flex: 1 1 auto;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.map-container.fullscreen {
  position: fixed;
  inset: 0;
  z-index: 9999;
  margin: 0;
  padding: 10rpx;
  border-radius: 0;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.location-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 8rpx 15rpx;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 15rpx;
  font-size: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.3);
  transition: all 0.3s ease;
}

.location-btn:active {
  transform: scale(0.95);
  background-color: #45a049;
}

.location-icon {
  font-size: 22rpx;
}

.location-text {
  font-size: 20rpx;
  font-weight: 500;
}

.map-title {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.device-count {
  font-size: 18rpx;
  color: #666;
}

.user-location {
  margin: 8rpx 0;
  padding: 12rpx 15rpx;
  background-color: #e8f5e8;
  border-radius: 6rpx;
  border-left: 3rpx solid #4CAF50;
}

.location-text {
  font-size: 20rpx;
  color: #2E7D32;
  font-weight: 500;
}

.map-component {
  flex: 1 1 auto;
  width: 100%;
  height: 100% !important;
  min-height: 200px;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  z-index: 1;
}

.map-legend {
  position: absolute;
  bottom: 15rpx;
  left: 15rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8rpx;
  padding: 12rpx 15rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 15rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.legend-color {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  
  &.online { background-color: #4CAF50; }
  &.offline { background-color: #9E9E9E; }
  &.fault { background-color: #F44336; }
  &.factory { background-color: #ffa500; }
}

.legend-text {
  font-size: 20rpx;
  color: #333;
}

/* 控制面板样式 */
.control-panel {
  height: 350rpx;
  background-color: #ffffff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 25rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.update-hint {
  margin-top: 8rpx;
  font-size: 18rpx;
  color: #999;
}

.panel-title {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.legend {
  display: flex;
  gap: 15rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.legend-dot {
  width: 10rpx;
  height: 10rpx;
  border-radius: 50%;
  
  &.online { background-color: #4cd964; }
  &.offline { background-color: #999999; }
  &.fault { background-color: #dd524d; }
  &.factory { background-color: #ffa500; }
}

.legend-text {
  font-size: 18rpx;
  color: #666;
}

.device-list {
  height: 250rpx;
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.device-info {
  flex: 1;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.status-text {
  font-size: 18rpx;
  color: #666;
}

.device-name {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
}

.device-status {
  width: 10rpx;
  height: 10rpx;
  border-radius: 50%;
  
  &.online { background-color: #4cd964; }
  &.offline { background-color: #999999; }
  &.fault { 
    background-color: #dd524d;
    animation: fault-blink 1.5s infinite;
  }
}

.fault-device {
  background-color: #fff5f5;
  border-left: 3rpx solid #ff4444;
  box-shadow: 0 2rpx 8rpx rgba(255, 68, 68, 0.1);
}

.fault-name {
  color: #ff4444 !important;
  font-weight: bold;
}

.fault-status {
  color: #ff4444 !important;
  font-weight: bold;
}

.fault-location {
  color: #ff6666 !important;
}

.fault-data-item {
  color: #ff4444 !important;
  font-weight: bold;
}

@keyframes fault-blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.3; }
}

.device-location {
  font-size: 18rpx;
  color: #666;
  margin-bottom: 8rpx;
  display: block;
}

.device-data {
  display: flex;
  gap: 15rpx;
  margin-bottom: 8rpx;
}

.data-item {
  font-size: 16rpx;
  color: #999;
}

.predict-btn {
  padding: 8rpx 15rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 18rpx;
  font-weight: bold;
  margin-top: 5rpx;
}

.predict-btn:disabled {
  background: #ccc;
  color: #999;
}

/* 底部统计样式 */
.bottom-stats {
  display: flex;
  background-color: #ffffff;
  padding: 15rpx 0;
  border-top: 1rpx solid #f0f0f0;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
  
  &.online { color: #4cd964; }
  &.offline { color: #999999; }
  &.fault { color: #dd524d; }
}

.stat-label {
  font-size: 16rpx;
  color: #666;
}

/* 预测结果弹窗样式 */
.prediction-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.modal-content {
  background-color: #fff;
  border-radius: 20rpx;
  width: 100%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
}

.close-btn {
  font-size: 40rpx;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.device-info-section,
.factory-analysis-section,
.prediction-result-section,
.recommendations-section {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.info-item {
  display: flex;
  margin-bottom: 15rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 24rpx;
  color: #666;
  width: 120rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 24rpx;
  color: #333;
  flex: 1;
}

.factory-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.factory-item {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  border-left: 4rpx solid #4CAF50;
}

.factory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.factory-name {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.factory-distance {
  font-size: 20rpx;
  color: #666;
  background-color: #e9ecef;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
}

.factory-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.factory-industry,
.factory-pollutants {
  font-size: 20rpx;
  color: #666;
}

.factory-risk {
  font-size: 20rpx;
  font-weight: bold;
  
  &.high { color: #ff4444; }
  &.medium { color: #ffa500; }
  &.low { color: #4cd964; }
}

.prediction-content {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.prediction-text {
  font-size: 24rpx;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
}

.recommendations-list {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.recommendation-item {
  font-size: 22rpx;
  line-height: 1.5;
  color: #333;
  padding: 10rpx 15rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border-left: 3rpx solid #4CAF50;
}

/* 污染状态样式 */
.pollution-status-section {
  margin-bottom: 20rpx;
}

.pollution-status {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 16rpx;
  border-radius: 12rpx;
  font-weight: 600;
  font-size: 28rpx;
}

.pollution-status.polluted {
  background: #ffe6e6;
  color: #d32f2f;
  border: 2rpx solid #ffcdd2;
}

.pollution-status.normal {
  background: #e8f5e8;
  color: #2e7d32;
  border: 2rpx solid #c8e6c9;
}

/* 污染源分析样式 */
.pollution-source-section {
  margin-bottom: 20rpx;
}

.suspected-factories {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.factory-item.suspected {
  background: #fff3e0;
  border: 2rpx solid #ffcc02;
  border-radius: 12rpx;
  padding: 16rpx;
}

.factory-item.suspected .factory-header {
  margin-bottom: 12rpx;
}

.factory-item.suspected .factory-name {
  color: #e65100;
  font-size: 28rpx;
}

.pollution-probability {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff5722;
  background: #ffebee;
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
}

.factory-item.suspected .factory-details {
  margin-bottom: 12rpx;
}

.pollution-reason {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
  font-style: italic;
}

/* AI服务开关样式 */
.panel-controls {
  display: flex;
  align-items: center;
}

.ai-service-toggle {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  background-color: #f8f9fa;
  border-radius: 20rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.ai-service-toggle:active {
  transform: scale(0.95);
}

.toggle-text {
  font-size: 20rpx;
  color: #666;
  font-weight: 500;
  transition: color 0.3s ease;
}

.toggle-text.active {
  color: #4CAF50;
  font-weight: 600;
}
</style>

